package com.example.tdemo.thread.lock;

import java.util.concurrent.locks.Lock;

 class Lock1 {
    public Lock1() {
    }


    public synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + "进入Lock1.method1");
        method2();
    }

    public synchronized void method2() {
        System.out.println(Thread.currentThread().getName() + "进入Lock1.method2");
    }
}

class Lock2 {
    public Lock2() {
    }

    public synchronized void method1() {
        System.out.println(Thread.currentThread().getName() + "进入Lock2.method1");
        method2();
    }

    public synchronized void method2() {
        System.out.println(Thread.currentThread().getName() + "进入Lock2.method2");
    }
}


public class LockDemo {


    public static void main(String[] args) {
        // 公平锁：按顺序获取锁 FIFO队列等待获取锁
        // 非公平锁：不保证顺序，直接尝试获取锁，没抢到，再走队列获取
        // 非公平锁性能高，公平锁线程不会饿死


        // 可重入锁  线程已经获取到锁，该锁所管理的所有代码块，重复执行，该线程不需要在获取这把锁；可以避免死锁
        new Thread(() -> {
            Lock1 l1 = new Lock1();
//            Lock2 l2 = new Lock2();

            l1.method1();
//            l2.method1();
        }, "t1").start();

        new Thread(() -> {
            Lock1 l1 = new Lock1();
//            Lock2 l2 = new Lock2();

            l1.method1();
//            l2.method1();
        }, "t2").start();

    }


}
